import _config from './config'; // 导入私有配置
import store from '../../store/index.js'

export default function $http(options) {
	// const userInfo = uni.getStorageSync('user')
	// const {token, keyid, uid} = userInfo
	if(options.data === undefined){
		options.data = {}
	}
	let token = store.state.token
	if(!token){
		token = uni.getStorageSync('token')
		if(token){
			store.dispatch('setToken', token)
		}
	}
	if(!options.isLogin){
		options.data.userid = uni.getStorageSync('keyid')
		options.data.organizationid = uni.getStorageSync('orgid')
		options.data.departmentid = uni.getStorageSync('depid')
		options.data.usertype = 2
	}
	options.header = {
		'Authorization': 'Bearer ' + token
	}
	options.url = _config.url + options.url;
	// if(options.isToken === undefined || options.isToken){
	// 	options.data.token = token
	// 	options.data.ukeyid = keyid
	// 	options.data.uid = uid
	// }
	// options.data.usertype = 2
	// options.data['from'] = 2
	// options.data['fromwhat'] = 0
	// options.data['from'] = process.env.NODE_ENV === 'production' ? 2 : 0
	return new Promise((resolve, reject) => {
		// 进行url字符串拼接
		// 拦截请求
		if(!options.without){
			uni.showLoading({
				title: '加载中'
			})
		}
		_config.complete = (response) => {
			uni.hideLoading()
			//  request請求访问成功
			if (response.statusCode === 200) {
				// 接口请求成功
				if(options.ignore){
					resolve(response.data)
				}else if (response.data.code !== 0 && options.hideErrorModal !== true) {
					_error(response.data.code, response.data.msg)
					reject(response)
				}else{
					resolve(response.data);
				}
			} else {
				// 处理catch 请求，不在本页面之外处理，统一在这里处理
				if (options.handle) {
					reject(response)
				} else {
					// 登录态无效
					if(response.data.code === 10030 || response.data.code === 10031 || response.data.code === 10023 || response.data.code === 10022 || response.data.code === 10025){
						// uni.reLaunch({
						// 	url: '/pages/login/login'
						// })
					}
					try {
						Promise.reject(response).catch(err => {
							// console.error(err);  
							_page_error(response.statusCode || response.errMsg);
						});
					} catch (e) {
						console.log(e)
					}
				}
			}
		}
		// 开始请求
		console.dir(Object.assign({}, _config, options))
		uni.request(Object.assign({}, _config, options));
	})
}

// 接口錯誤
function _error(err, msg = '') {
	switch (err) {
		case 400:
			console.error(msg)
			// 错误码400的处理方式
			break;
	}
	uni.showModal({
		title: '错误',
		content: msg,
		showCancel: false
	});
}
// request 錯誤
function _page_error(err) {
	switch (err) {
		case 401:
			// 错误码401的处理方式
			console.error("请求被拒绝")
			// uni.reLaunch({
			// 	url: '/pages/login/login'
			// })
			console.log('本欲重登')
			uni.removeStorageSync('token')
			break;
		case 404:
			// 错误码404的处理方式
			console.error("没有找到页面")
			break;
		case 405:
			console.error("错误的请求")
			break;
	}
}
